<template>
  <BasicModal 
    v-bind="$attrs" @register="registerModal" 
    :title="getTitle" :minHeight="500" :width="700" @ok="handleSubmit" 
    destroyOnClose
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import {ref, computed, unref,useAttrs} from 'vue';
  import {BasicForm, useForm} from '/@/components/Form/index';
  import { cashierConfigFormSchema } from './payPassage.data';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { saveCashierConfig } from './payPassage.api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { listCashierTags, listPayPassage } from './payPassage.api';

  const { createMessage } = useMessage();
  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs()
  const isUpdate = ref(true);
  const rowId = ref('');
  const [registerForm, {setProps, updateSchema, resetFields, validate, setFieldsValue }] = useForm({
    labelWidth: 80,
    wrapperCol: {
      md: { span: 22 },
      sm: { span: 22 },
    },
    schemas: cashierConfigFormSchema,
    showActionButtonGroup: false,
  });
  
  const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    await resetFields();
    isUpdate.value = !!data?.isUpdate;
    setModalProps({ confirmLoading: false })
    setFieldsValue({
      ...data.record,
    })
    updateSchema([
      {
        field: 'passageId',
        label: '支付通道',
        component: 'ApiSelect',
        dynamicDisabled: ({ values }) => { return !!values.id},
        componentProps: ({ formModel, formActionType }) => {
          return {
            api: listPayPassage,
            params: {
              existAtPassage: '1',
              status: '1',
              appId: data.record.appId
            },
            showSearch: true,
            labelField: 'wayName',
            valueField: 'id',
            dropdownStyle: { maxHeight: '100vh', overflow: 'auto' },
          }
        }
      },
    ])

  });
  const getTitle = computed(() => isUpdate.value ? '编辑收银台配置' : '新增收银台配置');

  async function handleSubmit() {
    try {
      let values = await validate();
      setModalProps({confirmLoading: true});
      await saveCashierConfig(values, isUpdate.value);
      closeModal();
      createMessage.success(`${getTitle.value}成功`)
      emit('success', {isUpdate: unref(isUpdate), values: {...values, id: rowId.value}});
    } finally {
      setModalProps({confirmLoading: false});
    }
  }
</script>
